#include "Object.h"
#include "ObjPtrBase.h"
#include "ObjectIterator.h"

void Object::addInnerRef(ObjPtrBase* ptr)
{
	ptr->nextInner = innerRefs;
	innerRefs = ptr;
}

void Object::addOuterRef(ObjPtrBase* ptr)
{
	ptr->nextOuter = outerRefs;
	outerRefs = ptr;
}

void Object::removeOuterRef(ObjPtrBase* ptr)
{
	if(ptr == outerRefs)		// "ptr" is in the begin of the list
	{
		outerRefs = ptr->nextOuter;		
		return;
	}

	for(ObjPtrBase* p = outerRefs; p != 0; p = p->nextOuter)
	{
		if(p->nextOuter == ptr)	// "p" is previous for "ptr"
		{
			p->nextOuter = ptr->nextOuter;
		}
	}
}

Object::inner_iterator Object::inner_begin() const
{
	return inner_iterator(innerRefs);
}

Object::inner_iterator Object::inner_end() const
{
	return inner_iterator(0);
}

Object::outer_iterator Object::outer_begin() const
{
	return outer_iterator(outerRefs);
}
Object::outer_iterator Object::outer_end() const
{
	return outer_iterator(0);
}

Object::~Object()
{
	for(Object::outer_iterator it = outer_begin(); it!=outer_end(); it++)
	{
		//Object* obj = (*it);
		//obj->notify(this);
		it.objPtr->ptr = 0;
	}
}


////////for debugging
void printObjectInfo(std::ostream& out, const Object* object)
{
	if(object == 0)
	{
		out << "null" << std::endl;
		return;
	}

	out << "Name: " << object->getName() << std::endl;

	out << "Inner refs: ";
	printInnerRefs(out, object);
	out << std::endl;

	out << "Outer refs: ";
	printOuterRefs(out, object);
	out << std::endl;
}

void printInnerRefs(std::ostream& out, const Object* object)
{
	for(Object::inner_iterator it = object->inner_begin(); it!=object->inner_end(); it++)
	{
		Object* obj = (*it);
		if(obj) 
		{			
			out << obj->getName() << "  ";
		}
		else
		{
			out << "null  ";
		}
	}
}

void printOuterRefs(std::ostream& out, const Object* object)
{
	for(Object::outer_iterator it = object->outer_begin(); it!=object->outer_end(); it++)
	{
		Object* obj = (*it);
		if(obj) 
		{			
			out << obj->getName() << "  ";
		}
		else
		{
			out << "null  ";
		}
	}
}


